<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/2 0002
 * Time: 12:25
 */

namespace app\admin\controller;
use app\common\controller\AdminBase;
use think\db;
use  think\session;


class VotingRecord extends AdminBase
{

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     *  投票记录
     *
     */
    public function votingRecord($keyword = '', $page = 1){
        $map = [];
        if ($keyword) {
            $map['r.voteNickName|r.voteOpenId'] = ['=', "{$keyword}"];
        }
        $vote_record = Db::table('vote_record')
            ->alias('r')
            ->join('vote_player p','r.voteUserId = p.id')
            ->where($map)
            ->field('r.*,p.playerName')
            ->order('id DESC')->paginate(15, false, ['page' => $page]);
        return $this->fetch('votingRecord', ['vote_record'=>$vote_record, 'keyword' => $keyword]);
    }

   /**
    *
    * 投票统计
    */
    public function votingStatistics($keyword = '', $page = 1){
        $map = [];
        if ($keyword) {
            $map['nickName|openId'] = ['=', "{$keyword}"];
        }
        $array = [];
        $vote_record = Db::table('vote_record')
            ->field("count(*) as count,voteOpenId,voteNickName,voteIp")
            ->group("voteOpenId")
            ->paginate(15, false, ['page' => $page]);

        for($j = 0; $j <count($vote_record); $j++){
            $message = Db::table('vote_voter')->where($map)->where(['openId'=>$vote_record[$j]['voteOpenId']])->find();
            if($message != null){
                $array[$j]['status'] = 1;
            }else{
                $array[$j]['status'] = 0;
            }

            $array[$j]['openId'] = $vote_record[$j]['voteOpenId'];
            $array[$j]['nickName'] = $vote_record[$j]['voteNickName'];
            $array[$j]['voteIp'] = $vote_record[$j]['voteIp'];
        }
        return $this->fetch('votingStatistics', ['Statistics'=>$array, 'keyword' => $keyword,'vote_record'=>$vote_record]);
    }

    /**
     *  封禁/解禁
     *
     **/
    public function status(){
        $openId = $this->request->param('openId');
        $status = $this->request->param('status');
        $result = null;
        if($status == 1){// 封禁
            $result = Db::table('vote_voter')->insert(['openId'=>$openId]);
        }
        if($status == 0){ // 解禁
            $result = Db::table('vote_voter')->where(['openId'=>$openId])->delete();
        }
        if($result == 1){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }

}